package com.example.volunteeroa.controller;

import com.example.volunteeroa.JpaUtils.DeleteUtils;
import com.example.volunteeroa.entity.*;
import com.example.volunteeroa.repository.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;


@CrossOrigin//跨域
@RestController
@RequestMapping("api/volunteer")
public class VolunteerController {
    @Resource
    OrganizationRepository ORepository;
    @Resource
    VolunteerRepository VRepository;


    @GetMapping()
    public RestBean findAll(){
        List<Volunteer> all = VRepository.findAll();
        return new RestBean(200,"查询全部志愿者信息成功",all);
    }//查询全部

    @DeleteMapping()
    public RestBean deleteVolunteerByID(@RequestBody Volunteer volunteer){
        DeleteUtils.deleteVolunteer(ORepository,VRepository,volunteer);
        return new RestBean(200,"删除成功",null);
    }//通过志愿者id删除志愿者信息(实际上是移动到了默认分组)

    @PutMapping()
    public RestBean updateVolunteerInfo(@RequestBody Volunteer volunteer){
        Volunteer volunteer1 = VRepository.findById(volunteer.getVolunteerID()).get();
        Organization organization = ORepository.findById(volunteer1.getOrg().getOrgID()).get();
        volunteer.setOrg(organization);
        VRepository.save(volunteer);
        return new RestBean(200,"修改成功",null);
    }//修改志愿者信息

    @PostMapping("/{orgID}")
    public RestBean add(@RequestBody List<Volunteer> volunteer,@PathVariable Integer orgID){
        for(int i=0;i<volunteer.size();i++) {
            Volunteer volunteer1=volunteer.get(i);
            Optional<Organization> byId = ORepository.findById(orgID);
            Organization organization = byId.get();
            volunteer1.setOrg(organization);
            VRepository.save(volunteer1);
        }
        return new RestBean(200,"添加成功",null);
    }//添加一个新的志愿者信息
}
